package com.demon.mutehelper.awareness

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.util.Log
import android.widget.Toast
import com.demon.mutehelper.BuildConfig
import com.demon.mutehelper.bean.MuteRecord
import com.huawei.hms.kit.awareness.Awareness
import com.huawei.hms.kit.awareness.barrier.AwarenessBarrier
import com.huawei.hms.kit.awareness.barrier.BarrierStatus
import com.huawei.hms.kit.awareness.barrier.BarrierUpdateRequest
import com.huawei.hms.kit.awareness.barrier.LocationBarrier
import com.huawei.hms.kit.awareness.barrier.TimeBarrier
import com.huawei.hms.kit.awareness.capture.LocationResponse

class LocationAndTimeClient(private val context: Context) {
  @SuppressLint("MissingPermission") fun add(record: MuteRecord) {
    Awareness.getCaptureClient(context).location
      // 执行成功的回调监听
      .addOnSuccessListener { locationResponse: LocationResponse ->
        val location = locationResponse.location
        Log.i(
          TAG, "Longitude:" + location.longitude
              + ",Latitude:" + location.latitude
        )
      }
      // 执行失败的回调监听
      .addOnFailureListener { e: Exception? ->
        Log.e(TAG, "get location failed", e)
      }
    if ((record.startTime == null || record.startTime == 0L) && (record.lat == null || record.lon == null)) {
      return
    }
    // 时间
    val timeBarrier =
      record.startTime?.let { time -> TimeBarrier.duringTimePeriod(time, time + 1000 * 60) }
    //  定位
    val locationBarrier = getLocationBarrier(record.lat, record.lon)
    val intent = Intent(BARRIER_RECEIVE_ACTION)
    val pendingIntent =
      PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    val barrierReceiver = LocationAndTimeBarrierReceiver()
    context.registerReceiver(barrierReceiver, IntentFilter(BARRIER_RECEIVE_ACTION))
    val builder = BarrierUpdateRequest.Builder()
    val request = builder.apply {
      timeBarrier?.let {
        Log.d(TAG, "add time")
        addBarrier("${PREFIX_BARRIER_LABEL_TIME}_${record.id}", it, pendingIntent)
      }
      locationBarrier?.let {
        Log.d(TAG, "add location")
        addBarrier("${PREFIX_BARRIER_LABEL_LOCATION}_${record.id}", it, pendingIntent)
      }
    }.build()

    Awareness.getBarrierClient(context).updateBarriers(request)
      // 执行成功的回调监听
      .addOnSuccessListener {
        Toast.makeText(context.applicationContext, "add barrier success", Toast.LENGTH_SHORT)
          .show()
      }
      // 执行失败的回调监听
      .addOnFailureListener { e ->
        Toast.makeText(context.applicationContext, "add barrier failed", Toast.LENGTH_SHORT)
          .show()
        Log.e(TAG, "add barrier failed", e)
      }

  }

  fun deleteBarriers() {
    val deleteBuilder = BarrierUpdateRequest.Builder()
    val deleteRequest = deleteBuilder.deleteAll().build()
    Awareness.getBarrierClient(context).updateBarriers(deleteRequest).addOnSuccessListener {
      Log.d(TAG, "delete success")
    }.addOnFailureListener {
      Log.d(TAG, "delete failed")
    }
  }

  @SuppressLint("MissingPermission") fun getLocationBarrier(
    lat: Double?,
    lon: Double?
  ): AwarenessBarrier? {
    if (lat == null || lon == null) {
      return null
    }
    Log.d(TAG, "location lat $lat  lon $lon")
    return LocationBarrier.enter(lat, lon, 2000.0)
  }

  // 定义广播接收器，用于监听Barrier事件
  inner class LocationAndTimeBarrierReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
      val barrierStatus = BarrierStatus.extract(intent)
      val label = barrierStatus.barrierLabel
      when (barrierStatus.presentStatus) {
        BarrierStatus.TRUE -> {
          Log.i(TAG, "$label status:true")
          MuteEventHandler(context).handle()
          deleteBarrier(label)
        }
        BarrierStatus.FALSE -> Log.i(TAG, "$label status:false")
        BarrierStatus.UNKNOWN -> Log.i(TAG, "$label status:unknown")
      }
    }

    private fun deleteBarrier(label: String) {
      val builder = BarrierUpdateRequest.Builder()
      val request = builder.deleteBarrier(label).build()
      Awareness.getBarrierClient(context).updateBarriers(request).addOnSuccessListener {
        Log.d(TAG, "delete $label success")
      }.addOnFailureListener {
        Log.e(TAG, "delete $label failed", it)
      }
    }
  }

  class MuteEventHandler(context: Context) {
    private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    fun handle() {
      audioManager.adjustStreamVolume(AudioManager.STREAM_RING, AudioManager.ADJUST_MUTE, 0)
    }
  }

  companion object {
    private const val TAG = "LocationAndTimeClient"
    const val BARRIER_RECEIVE_ACTION = BuildConfig.APPLICATION_ID + "_LOCATION_AND_TIME"
    const val PREFIX_BARRIER_LABEL_LOCATION = "location enter barrier"
    const val PREFIX_BARRIER_LABEL_TIME = "period of day barrier"
  }
}